<template>
    <div class="home-contianer">
      <el-scrollbar style="height:100%;">
        <div class="title-box"> 
            <div>
                今日销售实况
                <el-tooltip class="item" effect="dark" content="统计为付款时间从凌晨到更新时间内订单数据，未扣除退款数据" placement="top-start">
                  <el-button icon="el-icon-warning-outline" circle size="mini" type="text"></el-button>
                </el-tooltip>
            </div>
            <div>
                <span style="font-size: 14px;">更新时间：{{currentTime}}</span>
                <el-button size="mini" icon="el-icon-refresh" @click="refesh">刷新</el-button>
            </div>
        </div>
        <div data-v-542f4644 class="ivu-row">
            <div
              v-for="item in transformToday"
              :key="item.key"
              class="ivu-col ivu-col-span-3"
            >
              <div class="top-box">
                <div class="right-box">
                    <!-- 图标 -->
                    <img :src="item.src" alt="">
                </div>
                <div class="left-box">
                    <div class="item-name">
                    {{ item.name }}
                    </div>
                    <div class="total">
                        ￥{{
                        (item.amount + "").replace(
                            /(\d{1,3})(?=(\d{3})+(?:$|\.))/g,
                            "$1,"
                        )
                        }}
                    </div>
                    <div>成交金额</div>
                </div>
              </div>
              <div class="bottom">
                <div>{{item.numberTitle}} {{item.number}}</div>
                <div>{{item.orderNumberTitle}} {{item.orderNumber}}</div>
              </div>
            </div>
        </div>

        <div class="title-box"> 
            <div>
                收入实况
                <el-tooltip class="item" effect="dark" content="统计为核销时间从凌晨到更新时间内订单数据，未扣除退款数据" placement="top-start">
                  <el-button icon="el-icon-warning-outline" circle size="mini" type="text"></el-button>
                </el-tooltip>
            </div>
            <div class="right-tag">
                <el-button type="primary" size="small" @click="currentDay">今日实时</el-button>
                <div class="date-box">
                    <!-- <el-button type="text">昨天</el-button>
                    <el-button type="text">7天</el-button>
                    <el-button type="text">30天</el-button>
                    <el-button type="text">日</el-button>
                    <el-button type="text">周</el-button> -->
                    <el-date-picker
                        v-model="mTime"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </div>
            </div>
        </div>
        <div data-v-542f4644 class="ivu-row">
            <div
              v-for="item in SalesData"
              :key="item.name"
              class="ivu-col ivu-col-span-6"
            >
              <div class="top-box">
                <div class="right-box">
                    <!-- 图标 -->
                    <img :src="item.src" alt="">
                </div>
                <div class="left-box">
                    <div class="item-name">
                    {{ item.name }}
                    </div>
                    <div class="total">
                        ￥{{
                        (item.amount + "").replace(
                            /(\d{1,3})(?=(\d{3})+(?:$|\.))/g,
                            "$1,"
                        )
                        }}
                    </div>
                    <div>{{item.moneyTitle}}</div>
                </div>
              </div>
              <div class="bottom">
                <div>{{item.numberTitle}} {{item.number}}</div>
                <div v-if="item.name == '滑雪课堂'">{{item.orderNumberTitle}} {{item.orderNumber}}</div>
              </div>
            </div>
        </div>

        <div>
            <div class="title-box">
                <div>
                    平台销售趋势
                    <el-tooltip class="item" effect="dark" content="统计为付款时间时段内订单数据，已扣除时段内发生退款数据；当数据为负数，代表时段内退款数据大于支付数据" placement="top-start">
                      <el-button icon="el-icon-warning-outline" circle size="mini" type="text"></el-button>
                    </el-tooltip>
                </div>
                <div class="right-tag">
                    <el-tabs
                        v-model="activeName"
                        type="card"
                        class="demo-tabs"
                    >
                        <el-tab-pane label="全业态" name="all"></el-tab-pane>
                        <el-tab-pane label="景区门票" name="ticket"></el-tab-pane>
                        <el-tab-pane label="雪具租赁" name="tool"></el-tab-pane>
                        <el-tab-pane label="酒店住宿" name="hotel"></el-tab-pane>
                        <el-tab-pane label="滑雪课堂" name="ski"></el-tab-pane>
                        <el-tab-pane label="文创特产" name="wenchuang"></el-tab-pane>
                    </el-tabs>
                    <el-button type="primary" size="small" icon="el-icon-upload2" @click="exportExl">导出报表</el-button>
                </div>
            </div>
            <div class="tag-box">
              <el-select v-model="channel" clearable placeholder="请选择渠道">
                <el-option
                  v-for="item in channelOptions"
                  :key="item.distributorCode"
                  :label="item.distributorName"
                  :value="item.distributorCode">
                </el-option>
              </el-select>
                <div class="date-box">
                    <!-- <el-button type="text">昨天</el-button>
                    <el-button type="text">7天</el-button>
                    <el-button type="text">30天</el-button>
                    <el-button type="text">日</el-button>
                    <el-button type="text">周</el-button> -->
                    <el-date-picker
                        v-model="bTime"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </div>
            </div>
        </div>

        <div class="charts-line">
            <div class="left">
                <div v-for="item in echartsLeft" :key="item.name" style="text-align: center;">
                    <div class="echartsTotal">
                        <img :src="item.src" alt="">
                        <span>{{item.title}}</span>
                    </div>
                    <h2>{{ item.title == '金额总计' ? '￥'+ item.total : item.total}}</h2>
                </div>
            </div>
            <div class="right" id="charts-line" style="height:500px;"></div>
            <div class="sum" v-if="false">
              <el-table :data="tableData" height="100%" :header-cell-style="{ 'text-align': 'center','font-size': '18px' }" :cell-style="{ 'text-align': 'center' }">
                <el-table-column label="票务产品分类实时收入排名">
                  <el-table-column
                    prop="date"
                    label="产品分类"
                    width="180">
                  </el-table-column>
                  <el-table-column
                    prop="name"
                    label="收入金额"
                    width="100">
                  </el-table-column>
                  <el-table-column
                    prop="address"
                    width="100"
                    label="销售数量">
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
        </div>
      </el-scrollbar>
    </div>
  </template>
  
  <script>
  import "echarts/map/js/china";
  var echarts = require("echarts");
  
  export default {
    components: {
      VolBox: () => import("@/components/basic/VolBox.vue"),
      VolForm: () => import("@/components/basic/VolForm.vue")
    },
  
    data() {
      return {
        n: 90,
        timer: "",
        refreshData: null,
        model: false,
        value1: "1",
        fifth: null,
        activeName: 'all',
        echartsLeft: [{
            src: 'https://cdnv2.lishicloud.com/biz/p/beikong/bIcon.png',
            title: '金额总计',
            total: ''
        },{
            src: 'https://cdnv2.lishicloud.com/biz/p/beikong/gIcon.png',
            title: '数量总计',
            total: ''
        },{
            src: 'https://cdnv2.lishicloud.com/biz/p/beikong/yIcon.png',
            title: '订单总计',
            total: ''
        }],
        currentTime: '',
        transformToday: [{
          name: '平台总览',
          key: 'salesTodayTotal',
          numberTitle: '支付产品数',
          orderNumberTitle: '支付订单数',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/incIcon.png',
          amount: 0,
          number: 0,
          orderNumber: 0,
        },{
          name: '景区票务',
          key: 'ticketToday',
          numberTitle: '支付门票数',
          orderNumberTitle: '支付订单数',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/ticIcon.png',
          amount: 0,
          number: 0,
          orderNumber: 0,
        },{
          name: '酒店住宿',
          key: 'hotelToday',
          numberTitle: '支付间夜数',
          orderNumberTitle: '支付订单数',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/hotIcon.png',
          amount: 1,
          number: 0,
          orderNumber: 0,
        },{
          name: '滑雪课堂',
          key: 'skiToday',
          numberTitle: '支付学员数',
          orderNumberTitle: '支付订单数',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/sclaIcon.png',
          amount: 1,
          number: 0,
          orderNumber: 0,
        },{
          name: '文创特产',
          key: 'wenChuangToday',
          numberTitle: '支付商品数',
          orderNumberTitle: '支付订单数',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/culIcon.png',
          amount: 1,
          number: 0,
          orderNumber: 0,
        }], // 今日销售数据
        mTime: [],
        bTime: [],
        SalesData: [{
          name: '平台总览（不含酒店）',
          key: 'salesTodayTotal',
          numberTitle: '完成产品数',
          moneyTitle: '完成金额',
          orderNumberTitle: '',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/incIcon.png',
          amount: 0,
          number: 0,
          orderNumber: 0,
        },{
          name: '景区票务（不含车撬）',
          key: 'ticketToday',
          numberTitle: '核销票数',
          moneyTitle: '核销金额',
          orderNumberTitle: '',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/ticIcon.png',
          amount: 0,
          number: 0,
          orderNumber: 0,
        },{
          name: '雪车雪橇',
          key: 'cheQiaoToday',
          numberTitle: '核销人次',
          moneyTitle: '核销金额',
          orderNumberTitle: '',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/ticIcon.png',
          amount: 0,
          number: 0,
          orderNumber: 0,
        },{
          name: '雪具租赁',
          key: 'snowGearToday',
          numberTitle: '雪卡人次',
          moneyTitle: '租赁金额',
          orderNumberTitle: '',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/ticIcon.png',
          amount: 1,
          number: 0,
          orderNumber: 0,
        },{
          name: '酒店住宿',
          key: 'hotelToday',
          numberTitle: '入住房间数',
          moneyTitle: '入住金额',
          orderNumberTitle: '',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/hotIcon.png',
          amount: 1,
          number: 0,
          orderNumber: 0,
        },{
          name: '滑雪课堂',
          key: 'skiToday',
          numberTitle: '完成学员数',
          moneyTitle: '完成金额',
          orderNumberTitle: '教练出导数',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/sclaIcon.png',
          amount: 1,
          number: 0,
          orderNumber: 0,
        },{
          name: '文创特产',
          key: 'wenChuangToday',
          numberTitle: '确认商品数',
          moneyTitle: '完成金额',
          orderNumberTitle: '',
          src: 'https://cdnv2.lishicloud.com/biz/p/beikong/datacenter/culIcon.png',
          amount: 1,
          number: 0,
          orderNumber: 0,
        }], // 收入实况
        currentDate: '',
        channelOptions: [], // 渠道下拉
        channel: '',
        moneyTotal: '', // 总金额
        numTotal: '', // 总数量
        orderNumTotal: '', // 总订单数量
        legendData: ['金额','数量','订单'], // echarts数据
        xAxisData: [],
        echartsData: [],
        tableData: [{
          date: '2016-05-02',
          name: '王小虎',
          address: '1'
        }, {
          date: '2016-05-04',
          name: '王小虎',
          address: '1'
        }, {
          date: '2016-05-01',
          name: '王小虎',
          address: '1'
        }, {
          date: '2016-05-03',
          name: '王小虎',
          address: '1'
        }]
      };
    },
    created() {
      this.getCurrentTime();
      this.getEchartsData();
      this.getChannelList();
    },
    beforeDestroy() {
      clearInterval(this.refreshData);
      this.refreshData = null;
    },
    watch: { 
      'bTime': {
        handler() {
          this.getEchartsData();
        },
        deep: true
      },
      'mTime': {
        handler() {
          this.getMiddleData();
        },
        deep: true
      },
      'channel': {
        handler() {
          this.getEchartsData();
        },
      },
      'activeName': {
        handler() {
          this.getEchartsData();
        },
      }
    },
    mounted() {
      this.refreshData = setInterval(() => {
      }, 1000 * 60 * 60);
      this.fifth = setTimeout(() => {
        clearTimeout(this.timer);
      }, 1000 * 60 * 5);
      this.getData();
      this.getMiddleData();
    },
    methods: {
      // 今日销售实况数据获取
      getData() {
        this.http.get("api/Small_statistic_sale_order/getSalesToday").then(res => {
          this.transformToday.forEach((item,index) => {
            this.transformToday[index] = Object.assign(item,res[item.key])
          })
        });
      },
      // 刷新
      refesh() {
        var dd = new Date();
        dd.setDate(dd.getDate());
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1;
        var d = dd.getDate();
        var hours = dd.getHours();
        var minutes = dd.getMinutes();
        var seconds = dd.getSeconds();
        m = m < 10 ? "0" + m : m;
        d = d < 10 ? "0" + d : d;
        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        var time = y + "-" + m + "-" + d + " " + hours + ':' + minutes + ':' + seconds;
        this.currentTime = time;
        this.getData();
      },
      currentDay() {
        this.mTime = [this.currentDate,this.currentDate];
      },
      // 时间
      getCurrentTime (dates) {
          var dd = new Date();
          var n = dates || 0;
          dd.setDate(dd.getDate() + n);
          var y = dd.getFullYear();
          var m = dd.getMonth() + 1;
          var d = dd.getDate();
          var hours = dd.getHours();
          var minutes = dd.getMinutes();
          var seconds = dd.getSeconds();

          m = m < 10 ? "0" + m : m;
          d = d < 10 ? "0" + d : d;
          hours = hours < 10 ? "0" + hours : hours;
          minutes = minutes < 10 ? "0" + minutes : minutes;
          seconds = seconds < 10 ? "0" + seconds : seconds;
          this.currentDate = y + "-" + m + "-" + d;
          var time = y + "-" + m + "-" + d + " " + hours + ':' + minutes + ':' + seconds;
          this.currentTime = time;
          this.mTime = [this.currentDate,this.currentDate];
          this.bTime = [this.currentDate,this.currentDate];
      },
      getMiddleData () {
        let startTime  = this.mTime[0] + ' 00:00:00';
        let endTime  = this.mTime[1] + ' 23:59:59';
        this.http.get(`api/Small_statistic_sale_order/GetSalesData?startTime=${startTime}&endTime=${endTime}`).then(res => {
          this.SalesData.forEach((item,index) => {
            this.SalesData[index] = Object.assign(item,res[item.key])
          })
        });
      },
      getEchartsData() {
        let params = {
          startTime: this.bTime[0] + ' 00:00:00',
          endTime: this.bTime[1] + ' 23:59:59',
          channel: this.channel,
          type: this.activeName,
        }
        this.http.post("api/Small_statistic_sale_order/getTicketTrend",params).then(res => {
          if(res) {
            this.echartsData = res
            this.xAxisData = []
            this.echartsLeft.forEach((item) => {
              item.total = 0
            })
            res.forEach((item) => {
              this.echartsLeft[0].total += item.amount
              this.echartsLeft[1].total += item.number
              this.echartsLeft[2].total += item.orderNumber
              this.xAxisData.push(item.date)
            })
            this.echartsLeft[0].total = this.echartsLeft[0].total.toFixed(2);
            // this.$nextTick(() => {
            //   this.echartsLoad();
            // });
            setTimeout(() => {
              this.echartsLoad();
            })
          }
        });
      },
      // 渠道下拉
      getChannelList () {
        let params = {
          order: "desc",
          page: 1,
          rows: 30000,
          sort: "createDate"
        }
        this.http.post("api/Channels/getPageData",params).then(res => {
          this.channelOptions = res.rows;
          this.channelOptions.unshift({
            distributorCode: 'erp',
            distributorName: '窗口柜台'
          })
        });
      },
      // 导出
      exportExl() {
        let params = {
          startTime: this.bTime[0] + ' 00:00:00',
          endTime: this.bTime[1] + ' 23:59:59',
          channel: this.channel,
          type: this.activeName,
        }
        this.http.post("api/Small_statistic_sale_order/exportByTicketTrend",params).then(result => {
          if (!result.status) {
            return this.$error(result.message);
          }
          let path = 'api/Small_statistic_sale_order/DownLoadFile';
          this.download(
            this.http.ipAddress + path + "?path=" + result.data,
            '平台销售趋势表' + ".xlsx" // filePath
          );
        });
      },
      download(url, fileName) {
        let xmlResquest = new XMLHttpRequest();
        xmlResquest.open("GET", url, true);
        xmlResquest.setRequestHeader("Content-type", "application/json");
        xmlResquest.setRequestHeader(
          "Authorization",
          this.$store.getters.getToken()
        );
        let elink = document.createElement('a');
        xmlResquest.responseType = "blob";
        console.log(xmlResquest,'xmlResquest');
        xmlResquest.onload = function (oEvent) {
          if (xmlResquest.status != 200) {
            this.$error("下载文件出错了..");
            return;
          }
          let content = xmlResquest.response;
          elink.download = fileName; //+".xlsx";
          elink.style.display = "none";
          let blob = new Blob([content]);
          elink.href = URL.createObjectURL(blob);
          elink.click();
        };
        xmlResquest.send();
      },
      // echarts图加载
      echartsLoad() {
        var myChart = echarts.init(document.getElementById("charts-line"));
        /*获取地图数据*/
        myChart.showLoading();
        myChart.hideLoading();
        let option = {
          tooltip: {
            trigger: 'axis'
          },
          color: ['#4289ff','#5ad8a6','#f6bd16','pink','orange','black'],
          legend: {
              icon: 'rect',
              data: this.legendData,
              itemWidth: 25,
              itemHeight: 25,
              itemGap: 25,
              textStyle: {
              fontSize: 20,
            }
          },
          grid: {
              left: '3%',
              right: '5%',
              bottom: '3%',
              containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {
                title: '下载图片',
                name: '折线图'
              }
            }
          },
          xAxis: {
              type: 'category',
              boundaryGap: false,
              data: this.xAxisData,
              axisLabel: {
                show: true,
                interval: 0,
                rotate: 30
              }
          },
          // dataZoom:[
          //   {
          //     show: true,
          //     start: 0,
          //     end: 50
          //   }
          // ],
          yAxis: {
              type: 'log'
          },
          series: [
            {
              name: '订单',
              type: 'line',
              stack: 'Total',
              data: this.echartsData.map(item=> item.orderNumber)
            },
            {
              name: '数量',
              type: 'line',
              stack: 'Total',
              data: this.echartsData.map(item=> item.number)
            },
            {
              name: '金额',
              type: 'line',
              stack: 'Total',
              data: this.echartsData.map(item=> item.amount)
            },
          ]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        window.addEventListener("resize", function() {
          myChart.resize();
        });
      }
    },
    destroyed() {
      clearInterval(this.timer);
      clearTimeout(this.fifth);
    }
  };
  </script>
  
<style lang="less" scoped>
.home-contianer {
    background: #efefef;
    width: 100%;
    height: 100%;
    padding: 15px;
    .title-box{
        font-size: 22px;
        font-weight: bold;
        padding: 0 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 0 0 15px 0;
        .right-tag {
            display: flex;
            .el-button {
                margin: 0 20px;
                height: 40px;
            }
        }
    }
    .tag-box {
        border-bottom: 1px solid #434242;
        border-top: 1px solid #434242;
        padding: 15px 0;
        display: flex;
        justify-content: space-between;
    }
    .date-box {
        .el-button.is-active,
        .el-button:active,
        .el-button:focus, 
        .el-button:hover{
            color: #1890ff;
            font-weight: bold;
        }
        .el-button {
            color: rgb(120, 120, 120);
        }
    }
    .demo-tabs {
        display: inline;
    }
}
.ivu-row {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .ivu-col {
      border-radius: 5px;
      background: white;
      padding: 20px 20px;
      padding-bottom: 15px;
      font-size: 16px;
      flex: 0 0 calc((100% - 30px)/3);
      margin: 0 15px 15px 0;
    }
    .ivu-col:nth-child(3n) {
      /* 去除第3n个的margin-right */
      margin-right: 0;
    }
    .top-box {
        display: flex;
        flex-direction: row;
        padding-bottom: 20px;
        border-bottom: 1px solid #eee;
        align-items: center;
        .right-box {
            // border: 1px solid red;
        }
        .left-box {
            flex: 1;
            padding: 0 10px;
        }
    }
    .total {
      word-break: break-all;
      color: #282727;
      font-size: 30px;
      padding-bottom: 5px;
      vertical-align: middle;
      font-weight: bold;
      font-family: -apple-system, BlinkMacSystemFont, Segoe UI, PingFang SC,
        Hiragino Sans GB, Microsoft YaHei, Helvetica Neue, Helvetica, Arial,
        sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;
    }
    .item-name {
      position: relative;
      .icon {
        position: absolute;
        right: 0;
        top: -1px;
      }
    }
    .titleHover:hover {
      cursor: pointer;
      color: #2db7f5;
    }
    .bottom {
      padding-top: 15px;
    }
}
.ivu-col:hover {
    color: #ffffff;
    background-color: #4c9cff;
    .total {
        color: #fff;
    }
}
.charts-line {
    display: flex;
    background: white;
    width: 100%;
    padding-right: 20px;
    .left {
      font-size: 16px;
      font-weight: bold;
      align-self: center;
      padding: 0 20px;
      .echartsTotal {
          white-space: nowrap;
          display: flex;
          align-items: center;
      }
    }
    .right {
      flex: 1;
      background: white;
      padding: 20px 0;
      border-left: 1px solid #434242;
      padding-right: 20px;
    }
}
</style>
  